package com.algebra.active.controller;

import cn.hutool.json.JSONUtil;
import com.algebra.active.domain.NodeRoleRel;
import com.algebra.active.domain.SysRole;
import com.algebra.active.domain.WorkflowNode;
import com.algebra.active.service.*;
import com.algebra.active.util.ServiceApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * @author al
 * @date 2020/2/21 10:57
 * @description 工作流 v2.0 服务接口
 */
@Slf4j
@RestController
@Api(value = "工作流 v2.0 配置接口", tags = "工作流 v2.0 配置接口")
public class BaseWorkflowConfigController {

    @Autowired
    INodeOprService nodeOprService;

    @Autowired
    NodeRoleRelService nodeRoleRelService;

    @Autowired
    WorkflowNodeService nodeService;

    @Autowired
    SysRoleService roleService;


    @GetMapping("/configWorkflowNode")
    @ApiOperation("工作流发布-节点和路由")
    public ServiceApiResult<String> configWorkflowNode(@RequestParam("procDefKey") String procDefKey) {
        ServiceApiResult<String> result = new ServiceApiResult<>();
        log.info("工作流发布-节点和路由，请求参数：procDefKey = {}", procDefKey);
        try {
            nodeOprService.getNodeInfo(procDefKey);
            result.setMessage("配置成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("配置工作流信息异常："+e.getMessage());
        }
        return result;
    }

    @PostMapping("/configWorkflowRole")
    @ApiOperation("工作流发布-节点关联角色")
    public ServiceApiResult<String> configWorkflowRole(@RequestParam("procDefId") String procDefId, @RequestBody NodeRoleRel nodeRoleRel) {
        ServiceApiResult<String> result = new ServiceApiResult<>();
        log.info("工作流发布-节点关联角色，请求参数： procDefId = {}, nodeRoleRel = {}", procDefId, JSONUtil.toJsonStr(nodeRoleRel));
        try {
            if(nodeRoleRel.getNodeId() == null || nodeRoleRel.getRoleId() == null){
                result.setSuccess(false);
                result.setMessage("必填字段为空！");
                return result;
            }
            WorkflowNode workflowNode = nodeService.selectByPrimaryKey(nodeRoleRel.getNodeId(), procDefId);
            SysRole sysRole = roleService.selectByPrimaryKey(nodeRoleRel.getRoleId());
            if(workflowNode == null || sysRole == null){
                result.setSuccess(false);
                result.setMessage("信息不存在！");
                return result;
            }

            nodeRoleRel.setCreateAt(new Date());
            nodeRoleRelService.insertSelective(nodeRoleRel);
            result.setMessage("配置成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("配置工作流信息异常："+e.getMessage());
        }
        return result;
    }


}
